import { useState, useEffect } from 'react';
import { Table, Select, Space, Form, message } from 'antd';
import { MainLayout } from '~/layouts/MainLayout';
import { categoryApi } from '~/services/api';
import { Cascader } from 'antd';  // 添加 Cascader 导入

export default function Categories() {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [options, setOptions] = useState<any[]>([]);

  // 加载级联数据
  const loadData = async (selectedOptions: any[]) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    try {
      const res = await categoryApi.list({
        parentId: targetOption.value,
        parentLevel: targetOption.level.toString()
      });

      targetOption.loading = false;
      targetOption.children = (res.data?.items || []).map((item: any) => ({
        label: item.name,
        value: item.id.toString(),
        level: targetOption.level + 1,
        isLeaf: targetOption.level >= 5  // 第六级没有子级
      }));
      setOptions([...options]);
    } catch (error) {
      message.error('获取子分类失败');
    }
  };

  // 初始化一级分类
  // 修改 initCategories 方法
  const initCategories = async (page = 1, size = 10) => {
    setLoading(true);
    try {
      const res = await categoryApi.list({});
      const level1Options = (res.data?.items || []).map((item: any) => ({
        label: item.name,
        value: item.id.toString(),
        level: 1,
        isLeaf: false
      }));
      setOptions(level1Options);
      setData(res.data?.items || []);
      setPagination({
        current: page,
        pageSize: size,
        total: res.data?.total || 0
      });
    } catch (error) {
      message.error('获取分类失败');
    }
    setLoading(false);
  };

  useEffect(() => {
    initCategories();
  }, []);

  // 处理级联选择变化
  // 添加分页状态
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 修改 fetchData 和相关函数中的数据处理
  // 添加选中路径状态
  const [selectedPath, setSelectedPath] = useState<any[]>([]);

  // 修改 handleCascaderChange
  const handleCascaderChange = async (value: string[], selectedOptions: any[]) => {
    setSelectedPath(selectedOptions || []);
    if (selectedOptions && selectedOptions.length > 0) {
      setLoading(true);
      const lastOption = selectedOptions[selectedOptions.length - 1];
      try {
        const res = await categoryApi.list({
          parentId: lastOption.value,
          parentLevel: lastOption.level.toString(),
        });
        const processedData = (res.data?.items || []).map((item: any, index: number) => ({
          ...item,
          key: `${item.id}_${index}`
        }));
        setData(processedData);
        setPagination({
          ...pagination,
          current: 1,
          total: res.data?.total || 0
        });
      } catch (error) {
        message.error('获取分类数据失败');
      }
      setLoading(false);
    } else {
      initCategories();
    }
  };

  // 处理分页变化
  const handleTableChange = async (newPagination: any) => {
    setLoading(true);
    try {
      const lastOption = selectedPath[selectedPath.length - 1];
      const res = await categoryApi.list({
        parentId: lastOption?.value,
        parentLevel: lastOption?.level?.toString(),
      });
      setData(res.data?.items || []);
      setPagination({
        ...newPagination,
        total: res.data?.total || 0
      });
    } catch (error) {
      message.error('获取数据失败');
    }
    setLoading(false);
  };

  const columns = [
    {
      title: '层级',
      dataIndex: 'categoryLevel',
      key: 'categoryLevel',
      render: () => `第${(selectedPath.length + 1)}级`
    },
    {
      title: '分类名称',
      dataIndex: 'name',
      key: 'categoryName',
    },
    {
      title: '父类ID',
      dataIndex: 'parentId',
      key: 'parentId',
      render: (_: any, record: any) => {
        const lastOption = selectedPath[selectedPath.length - 1];
        return lastOption ? lastOption.value : '-';
      }
    },
    {
      title: '分类编码',
      dataIndex: 'code',
      key: 'categoryCode',
    },
  ];

  return (
    <MainLayout>
      <div className="bg-white p-6 rounded-lg">
        <div className="flex justify-between mb-4">
          <div>
            <h1 className="text-2xl mb-2">分类管理</h1>
            {selectedPath.length > 0 && (
              <div className="text-gray-500">
                当前位置：
                {selectedPath.map((option, index) => (
                  <span key={option.value}>
                    {index > 0 && ' > '}
                    {`${index + 1}级(${option.label})`}
                  </span>
                ))}
              </div>
            )}
          </div>
          <Cascader
            options={options}
            loadData={loadData}
            onChange={handleCascaderChange}
            changeOnSelect
            placeholder="请选择分类"
            style={{ width: 300 }}
          />
        </div>

        <Table
          columns={columns}
          dataSource={data}
          rowKey={(record) => record.id?.toString() || Math.random().toString()}
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
        />
      </div>
    </MainLayout>
  );
}